﻿// -----------------------------------------------------------------------
// <copyright file="PluginsService.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------



namespace TPTecnicas.MessageProcessor.Services
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel.Composition;
    using TPTecnicas.MessageProcessor.Common;
    using System.Configuration;
    using System.ComponentModel.Composition.Hosting;
    using TPTecnicas.MessageProcessor.Business;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class PluginsRepository
    {
        private readonly CompositionContainer _container;

        [ImportMany]
        private IEnumerable<Lazy<IRule, IDictionary<string, object>>> _lazyRules { get; set; }

        [ImportMany]
        private IEnumerable<Lazy<IAction, IDictionary<string, object>>> _lazyActions { get; set; }

        public PluginsRepository(IUniversityContext _context)
        {

            var catalog = new DirectoryCatalog(@ConfigurationManager.AppSettings["pluginsPath"]);
            _container = new CompositionContainer(catalog);
            _container.ComposeExportedValue("context", _context);

            _lazyRules = _container.GetExports<IRule, IDictionary<string, object>>();
            _lazyActions = _container.GetExports<IAction, IDictionary<string, object>>();

        }

        public IDictionary<string, IRule> GetRules(IEnumerable<string> ruleNames)
        {
            return _lazyRules.Where(r => ruleNames.Contains(r.Metadata["Name"])).ToDictionary(r => r.Metadata["Name"].ToString(), r => r.Value);
        }

        public IDictionary<string, IAction> GetActions(IEnumerable<string> actionNames)
        {
            return _lazyActions.Where(r => actionNames.Contains(r.Metadata["Name"])).ToDictionary(r => r.Metadata["Name"].ToString(), r => r.Value);
        }
    }
}
